package com.guaju.yueshangLife.viewmodel;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.guaju.yueshangLife.activity.SearchActivity;
import com.guaju.yueshangLife.dao.SearchHistoryModel;
import com.guaju.yueshangLife.global.BaseApplication;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by guaju on 2018/9/12.
 */

public class SearchbarVM extends BaseObservable{
    Context context;
    boolean editable;
    public View.OnKeyListener onKeyListener;
    Activity act;
    Fragment fragment;
    static EditText editText;

    public SearchbarVM(boolean editable, Fragment fragment) {
        this.editable = editable;
        this.fragment = fragment;
        act=fragment.getActivity();
        initOnKeyListener();
    }



    public SearchbarVM(Context context, boolean editable) {
        this.context=context;
        this.editable=editable;
        // Todo 加载数据
        if (context instanceof Activity){
            act = (Activity)context;
        }
        initOnKeyListener();
    }

    private void hideKeyboard() {
        if (act!=null){
        ((InputMethodManager) act.getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void onSearchBoxClick(View v){
        if (!editable){
        Intent intent = new Intent(context, SearchActivity.class);
        context.startActivity(intent);
        }
    }

    public void onTextChange(CharSequence s, int start, int before, int count){
        if (!TextUtils.isEmpty(s)){


        }
    }
    @BindingAdapter({"bind:onKeyEvent"})
    public static void onKeyEvent(EditText view, View.OnKeyListener onKeyListener) {
        editText=view;
        view.setOnKeyListener(onKeyListener);
    }

    private void initOnKeyListener() {
        onKeyListener = new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER&&event.getAction()== KeyEvent.ACTION_DOWN) {
                    hideKeyboard();
                    //加载数据,将数据存储到数据库
                    SearchHistoryModel search_history = new SearchHistoryModel(editText.getText().toString().trim());
                    BaseApplication.getLiteOrm().save(search_history);
                    return true;
                }
                return false;
            }
        };
    }
}
